package cn.zhiran.basic.controller;

import cn.zhiran.basic.util.AjaxResult;
import cn.zhiran.basic.util.FastDfsUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传文件接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //.jpg获取name的后缀名
            String substring = filename.substring(filename.lastIndexOf(".")+1);
            //调用工具类做上传操作
            String logo = FastDfsUtil.upload(file.getBytes(), substring);
            return AjaxResult.me().setResultObj(logo);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统异常，稍后重试");
        }

    }

    /**
     * 删除文件接口
     * @param path   /group1/M00/01/.....
     * @return
     */
    @DeleteMapping()
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){
        try {
            //切割group1签的/
            String pathTmp = path.substring(1);
            //获取组名
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            //获取文件路径
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);
            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统异常，稍后重试");
        }
    }



}
